package com.ts.api.http.market.channel;

import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.http.market.channel.entity.ChannelHuiRong;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarket;
import com.ts.api.module.api.convert.core.annotation.ApiChannelMarketConvertType;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.market.entity.ChannelMarketParameter;
import com.ts.api.module.api.convert.market.handler.ChannelMarketConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;
import java.util.Base64;
import java.util.Map;

/**
 * 惠融(白天)
 * 同业-大联登（不撞库）进件文档：https://fz6gwn68j3.feishu.cn/wiki/Dt32wKe5yik5pAk8qZ1cHRJcnBd 密码：27#6r763
 *
 * @author WJB
 */
@ApiChannelMarket(uniqueCode = "2bc724b1a5ed4fc59f73e0091b115a95", type = ApiChannelMarketConvertType.FEDERATE_USER_FORM)
public class HuiRongBaiFederate implements ChannelMarketConvertHandler {

    private static final String KEY = "3OJ19716zuw8U99XI6349HNw";
    private static final String ALGORITHM = "DES";
    private static final String TRANSFORMATION = "DES/ECB/PKCS7Padding";
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Override
    public ApiUserRequest parse(RequestVO requestVO) {
        String requestData = decrypt(KEY, requestVO.getStr("data"));

        ChannelHuiRong bean = JsonUtils.toBean(requestData, ChannelHuiRong.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(bean, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> response(ChannelMarketParameter channelMarketParameter, ApiBizStatus apiBizStatus) {
        if (apiBizStatus.hasBizSuc()) {
            return MapUtils.newHashMap(newMap -> {
                newMap.put("code", 200);
                newMap.put("msg", apiBizStatus.getBizMsg());
                newMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
                    dataMap.put("jumpUrl", channelMarketParameter.getUrl());
                    dataMap.put("status", 1);
                    dataMap.put("message", "推送成功");
                }));
            });
        }

        return MapUtils.newHashMap(newMap -> {
            newMap.put("code", 500);
            newMap.put("msg", apiBizStatus.getBizMsg());
            newMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
                dataMap.put("status", 2);
                dataMap.put("message", "失败");
            }));
        });
    }

    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    public static String decrypt(String password, String data) {
        if (password== null || password.length() < 8) {
            return null;
        }
        if (data == null){
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        // 性别 男/女
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "男", "0")
                    .when(sex, "女", "1")
                    .end("2");
            apiUserRequest.setSex(sexChoose);
        }

        // education 学历 :-1.初中及以下 0.高中/中专 1.大专 2.本科 3.硕士 4.博士
        // educationAttainment 学历
        // 1 初中及以下
        // 2 中专
        // 3 高中
        // 4 大专
        // 5 本科
        // 6 研究生及以上
        String educationAttainment = apiUserRequest.getEducationAttainment();
        if (ValidParam.isNotEmpty(educationAttainment)) {
            String value = ChooseEq.create()
                    .when(educationAttainment, "-1", "1")
                    .when(educationAttainment, "0", "3")
                    .when(educationAttainment, "1", "4")
                    .when(educationAttainment, "2", "5")
                    .when(educationAttainment, "3", "6")
                    .when(educationAttainment, "4", "6")
                    .end();
            apiUserRequest.setEducationAttainment(value);
        }

        // loadAmount 金额(万元)
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            apiUserRequest.setLoanAmount(ApiDictUtils.convertLoanAmount(loanAmount, false));
        }

        //  loanTerm 期限：1. 1个月 2. 3个月 3. 6个月 4. 9个月 5. 12个月 6. 24个月 7. 36个月 8. 36个月以上
        //  贷款期限
        //  1.3个月
        //  2.6个月
        //  3.12个月
        //  4.24个月
        //  5.36个月
        //  6.60个月
        String loanTerm = apiUserRequest.getLoanTerm();
        if (ValidParam.isNotEmpty(loanTerm)) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getLoanTerm(), "1", "1")
                    .when(apiUserRequest.getLoanTerm(), "2", "1")
                    .when(apiUserRequest.getLoanTerm(), "3", "2")
                    .when(apiUserRequest.getLoanTerm(), "4", "3")
                    .when(apiUserRequest.getLoanTerm(), "5", "3")
                    .when(apiUserRequest.getLoanTerm(), "6", "4")
                    .when(apiUserRequest.getLoanTerm(), "7", "5")
                    .when(apiUserRequest.getLoanTerm(), "8", "6")
                    .end();
            apiUserRequest.setLoanTerm(value);
        }

        // loanUse 用途：1.购车贷款 2.购房贷款 3.装修贷款 4.教育贷款 5.消费贷款 6.过桥贷款 7.结婚贷款 8.旅游贷款 9.医疗贷款 10.其他贷款
        // 1.旅游
        // 2.教育
        // 3.婚庆
        // 4.装修
        // 5.医疗
        // 6.个人消费
        String loanPurpose = apiUserRequest.getLoanPurpose();
        if (ValidParam.isNotEmpty(loanPurpose)) {
            String value = ChooseEq.create()
                    .when(loanPurpose, "1", "6")
                    .when(loanPurpose, "2", "6")
                    .when(loanPurpose, "3", "4")
                    .when(loanPurpose, "4", "2")
                    .when(loanPurpose, "5", "6")
                    .when(loanPurpose, "6", "6")
                    .when(loanPurpose, "7", "3")
                    .when(loanPurpose, "8", "1")
                    .when(loanPurpose, "9", "5")
                    .when(loanPurpose, "10", "6")
                    .end();
            apiUserRequest.setLoanPurpose(value);
        }

        // social 社保： 0.无社保 1.缴纳未满6个月 2.缴纳6个月以上
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "0", "1")
                    .when(socialSecurity, "1", "2")
                    .when(socialSecurity, "2", "3")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        // fund 公积金： 0.无公积金 1.缴纳未满6个月 2.缴纳6个月以上
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "0", "1")
                    .when(providentFund, "1", "2")
                    .when(providentFund, "2", "3")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        // insurance 保单：1.无保单 3.缴纳未满一年 4.缴纳一年以上
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "1", "1")
                    .when(insurancePolicy, "3", "2")
                    .when(insurancePolicy, "4", "3")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // car 车产情况： 1-无车产 2-有车产可抵押 3-有车不抵押
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "1", "1")
                    .when(carInfo, "2", "3")
                    .when(carInfo, "3", "2")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // house 房产情况：2-无房产 12-有房可抵押 13-有房不抵押
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "2", "1")
                    .when(realEstateInfo, "12", "3")
                    .when(realEstateInfo, "13", "2")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // profession 职业：1.民企员工 2.个体户  4.自由职业者 5.企业主 7.外企员工 8.公务员 9.事业单位员工 10.国企员工
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "1", "1")
                    .when(career, "2", "5")
                    .when(career, "4", "2")
                    .when(career, "5", "3")
                    .when(career, "7", "1")
                    .when(career, "8", "4")
                    .when(career, "9", "4")
                    .when(career, "10", "1")
                    .end();
            apiUserRequest.setCareer(value);
        }

        // business 营业执照：1.没办理 2.已办理，注册1年以内 3.已办理，注册满1年 4.已办理，注册满2年 5.已办理，注册满3年 6.已办理，注册满4年 7.已办理，注册满5年以上
        // 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        String bizLicenseYear = apiUserRequest.getBizLicenseYear();
        if (ValidParam.isNotEmpty(bizLicenseYear)) {
            String value = ChooseEq.create()
                    .when(bizLicenseYear, "1", "1")
                    .when(bizLicenseYear, "2", "2")
                    .when(bizLicenseYear, "3", "3")
                    .when(bizLicenseYear, "4", "3")
                    .when(bizLicenseYear, "5", "3")
                    .when(bizLicenseYear, "6", "3")
                    .when(bizLicenseYear, "7", "4")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        // credit 是否有逾期 0:当前无逾期 1:逾期一月内 2:逾期三个月内 3:逾期超过三个月
        // overdue 逾期状况
        // 1 无逾期
        // 2 当前有逾期
        // 3 一年以内无逾期
        String credit = apiUserRequest.getOverdue();
        if (ValidParam.isNotEmpty(credit)) {
            String value = ChooseEq.create()
                    .when(credit, "0", "1")
                    .when(credit, "1", "2")
                    .when(credit, "2", "2")
                    .when(credit, "3", "2")
                    .end();
            apiUserRequest.setOverdue(value);
        }

        // zhima 芝麻分：2、600分以下   3、600-650分 4、650-700分   5、700分及以上
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "2", "1")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "3")
                    .when(sesameCredit, "5", "4")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // incomeMonth  月收入：1.1000以下 2.1000-3000  3.3000-5000  4.5000-8000  5.8000-1.2万  6.1.2万-2万  7.2万-5万  8.5万-10万  9.10万以上
        // monthlySalary
        // 1	1000-3000
        // 2	3000-8000
        // 3	8000~15000
        // 4	15000~30000
        // 5	30000以上
        String monthlySalary = apiUserRequest.getMonthlySalary();
        if (ValidParam.isNotEmpty(monthlySalary)) {
            String value = ChooseEq.create()
                    .when(monthlySalary, "1", "1")
                    .when(monthlySalary, "2", "1")
                    .when(monthlySalary, "3", "2")
                    .when(monthlySalary, "4", "2")
                    .when(monthlySalary, "5", "3")
                    .when(monthlySalary, "6", "4")
                    .when(monthlySalary, "7", "5")
                    .when(monthlySalary, "8", "5")
                    .when(monthlySalary, "9", "5")
                    .end();
            apiUserRequest.setMonthlySalary(value);
        }

        // salaryType 工资发放形式：1-银行代发  3-现金发放
        // salaryPayMethod
        // 1 银行代发打卡
        // 2 现金收入
        // 3 个人转账
        String salaryPayMethod = apiUserRequest.getSalaryPayMethod();
        if (ValidParam.isNotEmpty(salaryPayMethod)) {
            String value = ChooseEq.create()
                    .when(salaryPayMethod, "1", "1")
                    .when(salaryPayMethod, "3", "2")
                    .end();
            apiUserRequest.setSalaryPayMethod(value);
        }
    }
}
